// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database();
  const _ = db.command;
  const $ = _.aggregate;
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  // 获取对评论的回复
  var msgListCmt = await db.collection('comment').aggregate().match({
      replyTo: openid,
      _openid: _.neq(openid)
    })
    .lookup({
      from: 'user',
      let: {
        cmterOpenid: '$_openid'
      },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$_openid', '$$cmterOpenid'])))
        .project({
          _id: 0,
          _openid: 1,
          nickName: 1,
          avatarUrl: 1
        })
        .done(),
      as: 'cmter'
    })
    .lookup({
      from: 'post',
      let: {
        originPostId: '$postId'
      },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$_id', '$$originPostId'])))
        .project({
          title: 1,
          content: 1
        })
        .done(),
      as: 'originPost'
    })
    .lookup({
      from: 'comment',
      let: {
        curId: '$_id',
        masterId: '$masterId'
      },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$_id', '$$masterId'])))
        .project({
          content: 1
        })
        .done(),
      as: 'masterCmt'
    })
    .project({
      time: 1,
      content: 1,
      cmterInfo: $.arrayElemAt(['$cmter', 0]),
      originPost: $.arrayElemAt(['$originPost', 0]),
      masterCmt: $.arrayElemAt(['$masterCmt', 0])
    })
    .end();

  // 查询对帖子的回复（直接回复我的帖子，不包括在我的帖子下对自己评论的回复）
  var msgListArticle = await db.collection('comment').aggregate()
    .match({
      replyTo: null,
      _openid: _.neq(openid)
    })
    .lookup({
      from: 'post',
      let: {
        postId: '$postId'
      },
      pipeline: $.pipeline().match(_.expr($.and([
          $.eq(['$_id', '$$postId']),
          $.eq(['$_openid', openid])
        ])))
        .project({
          title: 1,
          content: 1
        })
        .done(),
      as: 'originPost'
    })
    .match({
      'originPost.0': _.exists(true)
    })
    .lookup({
      from: 'user',
      let: {
        cmterOpenid: '$_openid'
      },
      pipeline: $.pipeline().match(_.expr($.eq(['$_openid', '$$cmterOpenid'])))
        .project({
          _id: 0,
          _openid: 1,
          nickName: 1,
          avatarUrl: 1
        })
        .done(),
      as: 'cmterInfo'
    })
    .project({
      time: 1,
      content: 1,
      cmterInfo: $.arrayElemAt(['$cmterInfo', 0]),
      originPost: $.arrayElemAt(['$originPost', 0])
    })
    .end()
  console.log('msg list', msgListCmt, msgListArticle);
  return {
    errCode: 0,
    data: msgListCmt.list.concat(msgListArticle.list).sort(cmp)
  };
}

/**
 * 比较时间排序，晚的排在前面
 * @param {*} a 对象1
 * @param {*} b 对象2
 */
function cmp(a, b) {
  var gt = -1,
    eq = 0,
    lt = 1;
  if (a.time > b.time) return gt;
  else if (a.time < b.time) return lt;
  else return eq;
}